package com.example.simpletask

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.drawable.BitmapDrawable
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.io.File
import java.io.FileOutputStream

class EditActivity : AppCompatActivity() {

    companion object {
//        由于启动此页面需要很多参数，所以提供静态方法供调用来启动
        fun start(context: Context, id: Int, content: String, steps: Int, stage: Int, attrs: Int) {
            val intent = Intent(context, EditActivity::class.java)
            intent.putExtra("id", id)
            intent.putExtra("content", content)
            intent.putExtra("steps", steps)
            intent.putExtra("stage", stage)
            intent.putExtra("attrs", attrs)
            context.startActivity(intent)
        }
    }

    lateinit var dbHelper: DbHelper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit)
        showPopwindow()

        dbHelper = DbHelper(this)

//        获取传过来的数据
        val id = intent.getIntExtra("id", -1)
        val content = intent.getStringExtra("content")
        var steps = intent.getIntExtra("steps", 1)
        var stage = intent.getIntExtra("stage", 0)

//        两个RecyclerView的渲染
        val stepslayoutManager = LinearLayoutManager(this)
        stepslayoutManager.orientation = RecyclerView.HORIZONTAL

        val stagelayoutManager = LinearLayoutManager(this)
        stagelayoutManager.orientation = RecyclerView.HORIZONTAL

        val stepsSelectors = findViewById<RecyclerView>(R.id.stepsSelectorsArea)
        stepsSelectors.layoutManager = stepslayoutManager
        val stepsAdapter = StepsSelectorAdapter(steps)
        stepsSelectors.adapter = stepsAdapter

        val stageSelectors = findViewById<RecyclerView>(R.id.stageSelectorsArea)
        stageSelectors.layoutManager = stagelayoutManager
        val stageAdapter = StageSelectorAdapter(stage)
        stageSelectors.adapter = stageAdapter

//        文本框
        val contentInput = findViewById<TextView>(R.id.contentInput)
        contentInput.text = content

//        确认按钮
        val confirmBtn = findViewById<ImageButton>(R.id.confirmBtn)
        confirmBtn.setOnClickListener {
            var outContent = contentInput.text.toString()
            if (outContent == "") {
                Toast.makeText(this, "任务内容不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            steps = stepsAdapter.getSteps()
            stage = stageAdapter.getStage()
            if (steps < stage) {
                stage = steps
            }
            dbHelper.updateMission(id, outContent, steps, stage, 0)
            MainActivity.start(this)
        }

        val cancelBtn = findViewById<ImageButton>(R.id.cancelBtn)
        cancelBtn.setOnClickListener {
            MainActivity.start(this)
        }

        val cameraBtn = findViewById<ImageButton>(R.id.cameraBtn)
        cameraBtn.setOnClickListener {
            openPopWindow()
        }
    }

    /**
     * 这下面的弹出菜单的代码和AddActivity中一样
     */
    private var popupWindow: PopupWindow? = null
    private var icontentView: View? = null
    lateinit var imageUri: Uri
    lateinit var outputImage: File
    val takePhoto: Int = 0
    val fromAlbum: Int = 1
    /**
     * 显示popupWindow
     */
    private fun showPopwindow() {
        //加载弹出框的布局
        icontentView = LayoutInflater.from(this@EditActivity).inflate(
            R.layout.activity_popupwindow, null  //111
        )
        popupWindow = PopupWindow(
            icontentView,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        popupWindow!!.isFocusable = true
        //取得焦点
        popupWindow!!.setBackgroundDrawable(BitmapDrawable())
        //点击外部消失
        popupWindow!!.isOutsideTouchable = true
        //设置可以点击
        popupWindow!!.isTouchable = true
        //进入退出的动画，指定刚才定义的style
        popupWindow!!.animationStyle = R.style.ipopwindow_anim_style

        val takePhotoBtn : Button = popupWindow!!.contentView
            .findViewById(R.id.takePhotoBtn)
        takePhotoBtn.setOnClickListener {
            // 创建File 对象，用于存储拍照后的照片
            outputImage = File(externalCacheDir,"output_image.jpg")
            if (outputImage.exists()){
                outputImage.delete()
            }
            outputImage.createNewFile()
            imageUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                FileProvider.getUriForFile(this,
                    "com.example.simpletask.fileprovider", outputImage)
            }else{
                Uri.fromFile(outputImage)
            }
            // 启动相机程序
            val intent = Intent("android.media.action.IMAGE_CAPTURE")
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri)
            startActivityForResult(intent, takePhoto)
        }

        val fromAlbumBtn : Button = popupWindow!!.contentView
            .findViewById(R.id.fromAlbumBtn)
        fromAlbumBtn.setOnClickListener {
            // 打开文件选择器
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            // 指定只显示图片
            intent.type = "image/*"
            startActivityForResult(intent, fromAlbum)
        }

        val deletePhotoBtn: Button = popupWindow!!.contentView
            .findViewById(R.id.deletePictureBtn)
        deletePhotoBtn.setOnClickListener {
            val alertDialog = AlertDialog.Builder(this).apply {
                setMessage("是否确定要删除?")
                setPositiveButton("确定") { dialog, which ->
                    val imageView = findViewById<ImageView>(R.id.imageView)
                    imageView.setImageBitmap(null)
                }
                setNegativeButton("取消") { dialog, which ->
                }
            }.show()


            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                .setTextColor(resources.getColor(R.color.red))
            alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                .setTextColor(resources.getColor(R.color.black))
        }
    }

    /**
     * 按钮的监听
     * @param v
     */
    fun openPopWindow() {
        //从底部显示
        popupWindow!!.showAtLocation(icontentView, Gravity.BOTTOM, 0, 0)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode){
            takePhoto ->{
                if (resultCode == Activity.RESULT_OK) {
                    // 将拍摄的照片显示出来
                    val bitmap =
                        BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))
                    val imageView: ImageView = findViewById(R.id.imageView)
                    imageView.setImageBitmap(rotateIfRequired(bitmap))
                    saveBitmap(bitmap)
                }
            }
            fromAlbum ->{
                if (resultCode == Activity.RESULT_OK && data != null){
                    data.data?.let { uri ->
                        val bitmap = getBitmapFromUri(uri)
                        val imageView: ImageView = findViewById(R.id.imageView)
                        imageView.setImageBitmap(bitmap)
                    }
                }
            }
        }
    }

    private fun getBitmapFromUri(uri: Uri) = contentResolver.openFileDescriptor(uri,"r")?.use {
        BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
    }

    private fun rotateIfRequired(bitmap: Bitmap): Bitmap {
        val exif = ExifInterface(outputImage.path) // 实例化图片信息类
        val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
        // 拿取图片的旋转角度,模式为标准顺时针。
        return when(orientation){
            ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap,90)
            ExifInterface.ORIENTATION_ROTATE_180 ->rotateBitmap(bitmap,180)
            ExifInterface.ORIENTATION_ROTATE_270 ->rotateBitmap(bitmap,270)
            else -> bitmap
        }
    }

    private fun rotateBitmap(bitmap: Bitmap, degree: Int): Bitmap {
        val matrix = Matrix()  // 矩阵对象
        matrix.postRotate(degree.toFloat()) // 顺时针旋转角度
        val rotatedBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.width,bitmap.height,matrix,true)
        // 截取图片并且使用矩阵对象旋转图片，同时也截取原图片
        bitmap.recycle() // 将不再需要的Bitmap 对象回收
        return rotatedBitmap
    }

    private fun saveBitmap(bmp: Bitmap)
    {
        var tags="saveBitmap"
        var f = System.currentTimeMillis() .toString()+ ".jpg"
        val path = Environment.getExternalStorageDirectory().toString() + "/DCIM/"
        val file: File = File(path + f)
        var fos: FileOutputStream? = null;
        try {
            fos = FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            Log.d(tags,"saved!")
        } catch (e:Exception) {
            Log.d(tags,"error!"+e.message)
        } finally {
            fos?.flush()
            fos?.close()
        }
    }
}